//
//  NQMainVc.m
//  KYDemo
//
//  Created by 李岚清 on 16/5/21.
//  Copyright © 2016年 李岚清. All rights reserved.
//
#import "HHLunBo.h"
#import "NQHomeVc.h"
#import "AppDelegate.h"
#import "NQNavVc.h"
#import "OKBottomView.h"
#import <Masonry/Masonry.h>
#import "OKSickDetailController.h"
#import "NQLeftMenuVc.h"
#import "LSSettingAndHelpTableViewController.h"
#import "NQLeftMenuHeaderView.h"
#import "NQUserInfoVc.h"
#import "NQDrawerManager.h"
#import "MOEntryViewController.h"
#import "MOProductViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "HHProvinceController.h"
#import "LSHTTPManager.h"
#import "NQRecord.h"
#import "NQUserInfo.h"
#import "NQCharityActivity.h"

#import <SDWebImage/UIImageView+WebCache.h>

#import "NQRecordManageVc.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "OKDoctorInfoController.h"
#import "MODoctorListController.h"


#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "LSHTTPManager.h"
#import <SVProgressHUD/SVProgressHUD.h>

//友盟统计
#import <UMMobClick/MobClick.h>

#import "MapViewController.h"
#import "OKLOLViewController.h"


@interface NQHomeVc () <OKBottomViewdelegate,NQLeftMenuVcDelegete,NQLeftMenuHeaderViewDelegate,CLLocationManagerDelegate,MKMapViewDelegate,HHLunBoDelegate>
{
    NSString *city;
    
}

@property (strong, nonatomic) UIView *topView;
@property (strong, nonatomic) UIView *PhotoView;
@property (strong, nonatomic) UIView *titleView;
@property (strong, nonatomic) OKBottomView *bottomView;
@property(nonatomic, strong) MOProductViewController *product;
@property(nonatomic, strong) MOEntryViewController *entry;

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLGeocoder *geocoder;


@property (nonatomic, strong) UILabel *weather_lab;//天气文字
@property (nonatomic, strong) UIButton *city_but;//城市按钮
@property (nonatomic, strong) UIView *cut_vie;//分割线
@property (nonatomic, strong) UILabel *temperature_lab;//温度
@property (nonatomic, strong) UILabel *date_lab;//日期
@property (nonatomic, strong) UIImageView *weather_img;//天气图像





@property (nonatomic, assign) BOOL isTap;
@property (nonatomic, strong) HHLunBo *LunBoView;
@property (nonatomic, strong) UIImageView *imgViewHH;
@property (nonatomic, strong) UILabel *labelHH;
//@property (nonatomic, strong) UILabel


@property (strong, nonatomic) NSMutableDictionary *data;

@end
static BOOL istap;

@implementation NQHomeVc
#pragma mark - 控制器View的生命周期

- (void)dealloc {
    NSLog(@"0000");
}

- (void)loadView {
    [super loadView];
     
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置背景色
    self.view.backgroundColor = NQColor(240, 238, 246);
    //设置标题
    self.navigationItem.title = @"快医";
    
    //设置菜单控制器的代理
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    NQLeftMenuVc *leftVc = (NQLeftMenuVc *)app.leftMenuVc;
    leftVc.delegate = self;
    
    //设置菜单控制器上的头部View的代理
    NQLeftMenuHeaderView *menuHeaderView = (NQLeftMenuHeaderView *)leftVc.tableView.tableHeaderView;
    menuHeaderView.delegate = self;
    
    //设置左上角按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"add"] style:UIBarButtonItemStylePlain target:self action:@selector(openDrawer:)];
    
    [self locationManager];
    [self requestLocationAutoorize];
    [self GetCurrentLocation];
    [self geocoder];
    
    // 添加子控件
    [self setupUI];
    self.bottomView.delegate = self;
    

    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"附近" style:UIBarButtonItemStylePlain target:self action:@selector(nearhospital)];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithTitle:@"直播" style:UIBarButtonItemStylePlain target:self action:@selector(askDoctor)];
//    UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithTitle:@"测试" style:UIBarButtonItemStylePlain target:self action:@selector(sure)];
    


    

    self.navigationItem.rightBarButtonItems = @[item1, item2];


    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeBtnTitle:) name:WheatherBtnChanged object:nil];
    
}

//友盟统计
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:NSStringFromClass([self class])];//("PageOne"为页面名称，可自定义)
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:NSStringFromClass([self class])];
}

- (void)nearhospital {
    [self.navigationController pushViewController:[[MapViewController alloc] init]  animated:YES];
    
}

- (void)askDoctor {
    
    OKLOLViewController *vc = [[OKLOLViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)sure {
    
    OKLOLViewController *vc = [[OKLOLViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)changeBtnTitle:(NSNotification *)noti {
    
//    NSLog(@"%@",noti);
    [self.city_but setTitle:noti.userInfo[@"key"] forState:UIControlStateNormal];
    self.city_name = noti.userInfo[@"key"];
    [self networkRequests];
}

#pragma mark - NQLeftMenuVcDelegete
//菜单控制器的点击cell跳转接口
- (void)leftMenuVcDidClickCell:(NSIndexPath *)indexPath{
        if (indexPath.section == 0 && indexPath.row == 0) {
            NSLog(@"点击---名医通申请");
            
            [self.navigationController pushViewController:self.entry animated:NO];
        }else if (indexPath.section == 0 && indexPath.row == 1){
            NSLog(@"点击---病历管理");
            NQRecordManageVc *recordVc = [[NQRecordManageVc alloc] init];
            recordVc.superVc = self;
            //解档病例数据源
            NSArray *recordArr = [NQRecord readRecordArr];
            //顺传
            if (recordArr) {
                recordVc.recordData = recordArr;
            }
            
            //解档用户基本信息
            NQUserInfo *userInfo = [NQUserInfo readUserInfo];
            if (userInfo) {
                recordVc.userInfo = userInfo;
            }
            
            [self.navigationController pushViewController:recordVc animated:NO];
            
            
        }else if (indexPath.section == 0 && indexPath.row == 2){
            NSLog(@"点击---关注医生");
            
            MODoctorListController *doc = [[MODoctorListController alloc]init];
            doc.title = @"关注医生";
            
            [self.navigationController pushViewController:doc animated:YES];
            
        }else if (indexPath.section == 1 && indexPath.row == 0){
            NSLog(@"点击---设置与帮助");
            
            LSSettingAndHelpTableViewController *SC = [[LSSettingAndHelpTableViewController alloc]init];
            
            [self.navigationController pushViewController:SC animated:NO];
        }else if (indexPath.section == 1 && indexPath.row == 1){
            NSLog(@"点击---关于产品");
            
            [self.navigationController pushViewController:self.product animated:NO];
            
        }else if (indexPath.section == 1 && indexPath.row == 2){
            NSLog(@"点击---分享给好友");
            
            [self share];
        }
}

#pragma mark - NQLeftMenuHeaderViewDelegate
//跳转到"个人信息修改控制器"
- (void)leftMenuHeaderViewSettingUserInfo:(NQLeftMenuHeaderView *)leftMenuHeaderView{
    [NQDrawer close];

    NQUserInfoVc *infoVc = [[NQUserInfoVc alloc] init];
    
    //解档用户数据模型
    NQUserInfo *userInfo = [NQUserInfo readUserInfo];
    //赋值用户数据
    infoVc.userInfo = userInfo;
    
    [self.navigationController pushViewController:infoVc animated:YES];
}

- (void)share {
    
    //1、创建分享参数
    NSArray* imageArray = @[[UIImage imageNamed:@"ruhua"]];
//    （注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"宗帅长的帅不帅?"
                                         images:imageArray
                                            url:[NSURL URLWithString:@"http://mob.com"]
                                          title:@"分享一下我们组长照片"
                                           type:SSDKContentTypeAuto];
        //2、分享（可以弹出我们的分享菜单和编辑界面）
        [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"确定"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           default:
                               break;
                       };
                       
                   }];
    }
}


- (void)setupUI {
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    [self.view addSubview:self.topView];
    [self.view addSubview:self.PhotoView];
    [self.view addSubview:self.titleView];
    [self.titleView addSubview:self.imgViewHH];
    [self.titleView addSubview:self.labelHH];
    [self.PhotoView addSubview:self.LunBoView];
    [self.view addSubview:self.bottomView];
    
    
    [self.imgViewHH mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleView).offset(10);
        make.centerY.equalTo(self.titleView);
        make.left.equalTo(self.titleView).offset(20);
    }];

    [self.labelHH mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleView).offset(10);
        make.centerY.equalTo(self.titleView);
        make.left.equalTo(self.imgViewHH).offset(22);
    }];

    
    // 添加约束
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@70.5);
    }];
    
    [self.PhotoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.topView.mas_bottom);
        make.height.equalTo(@(screenWidth* 3/5));
        
    }];
    
    [self.LunBoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.PhotoView);
        make.right.equalTo(self.PhotoView);
        make.top.equalTo(self.PhotoView);
        make.bottom.equalTo(self.PhotoView).offset(10);
        make.height.equalTo(self.PhotoView);
        make.width.equalTo(self.PhotoView);
    }];
    
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.PhotoView.mas_bottom);
        make.height.equalTo(@44.5);
        
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.titleView.mas_bottom);
        make.bottom.equalTo(self.view);

    }];
    
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_menu_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(openDrawer:)];
    
    leftBtn.imageInsets = UIEdgeInsetsMake(8, 8, 8, 8);
    
    self.navigationItem.leftBarButtonItem = leftBtn;

    
}

#pragma mark - 点击左上角按钮
- (void)openDrawer:(UIBarButtonItem *)leftBtn{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    NQNavVc *naVc = (NQNavVc *)self.navigationController;
    if (naVc.isOpen == YES) {
        [app.drawer close];
    }else{
        [app.drawer open];
    }
}

#pragma mark - 实现底部按钮的点击响应事件
- (void)btnClickCallBackWithButtonindex:(NSInteger)index {
    if (index == 6) {
        // 跳转到公益活动
        NQCharityActivity * charityVc = [[NQCharityActivity alloc] init];
        [self.navigationController pushViewController:charityVc animated:YES];
        return;
    }
    OKSickDetailController *vc = [[OKSickDetailController alloc] init];
    NSArray *sickArray = @[@"肿瘤", @"心血管", @"神经科", @"血液科", @"骨科"];
    vc.sickType = sickArray[index-1];
    vc.ci1_id = index;
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)clickBtn {
    [self.navigationController pushViewController:[[HHProvinceController alloc] init] animated:YES];
    istap = YES;
}


#pragma mark - 懒加载子控件
- (UIView *)topView {
    if (_topView == nil) {
        _topView = [[UIView alloc] init];
        
        //天气文字
        self.weather_lab = [[UILabel alloc] initWithFrame:CGRectMake(70, 20, 40, 30)];
        self.weather_lab.font = [UIFont systemFontOfSize:12];
        self.weather_lab.numberOfLines = 0;
        [_topView addSubview:self.weather_lab];
        
        //城市按钮
        self.city_but = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 - 106 , 26, 100, 18)];
        self.city_but.titleLabel.font = [UIFont systemFontOfSize:12];
        [self.city_but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.city_but setTitle:self.city_name forState:UIControlStateNormal];
        [self.city_but addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.city_but setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
        [_topView addSubview:self.city_but];
        
        //分割线
        self.cut_vie = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 - 0.5, 4, 1, 62)];
        self.cut_vie.backgroundColor = [UIColor grayColor];
        [_topView addSubview:self.cut_vie];
        
        //温度
        self.temperature_lab = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width*0.75 - 60, 16, 120, 20)];
        self.temperature_lab.textAlignment = NSTextAlignmentCenter;
        self.temperature_lab.font = [UIFont systemFontOfSize:12];
        [_topView addSubview:self.temperature_lab];
        
        //日期
        self.date_lab = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width*0.75 - 60, 32, 120, 20)];
        self.date_lab.textAlignment = NSTextAlignmentCenter;
        self.date_lab.font = [UIFont systemFontOfSize:12];
        [_topView addSubview:self.date_lab];
        
        //天气图像
        self.weather_img = [[UIImageView alloc] initWithFrame:CGRectMake(12, 12, 46, 46)];
        [_topView addSubview:self.weather_img];
        
        //请求天气
        [self networkRequests];
    }
    return _topView;
}

- (void)networkRequests {
    //请求天气
    LSHTTPManager *hetp = [LSHTTPManager sharedManager];
    
    NSString *key = @"17IvzuqmKrK1cGwNL6VQebF9";
    NSString *url = @"http://api.map.baidu.com/telematics/v3/weather";
    NSDictionary *parameters = @{@"location" : [NSString stringWithFormat:@"%@",self.city_name],
                                 @"output":@"json",
                                 @"ak":key};
    [hetp requestWithType:LSHTTPManagerTypeGet URLString:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull dataTask, NSDictionary *JSON) {
        NSString *date = [NSString stringWithFormat:@"日期: %@", JSON[@"date"]];
        
        NSArray *results = JSON[@"results"];
        
        //        NSLog(@"%@",JSON);
        
        NSDictionary *weather_data = results.firstObject;
        //            NSLog(@"%@",weather_data);
        NSArray *weathers = weather_data[@"weather_data"];
        NSDictionary *todayWeather_data = weathers.firstObject;
        NSString *weather = todayWeather_data[@"weather"];
        
        NSString *temperature = [NSString stringWithFormat:@"温度: %@", todayWeather_data[@"temperature"]];
        self.weather_lab.text = weather;
        self.temperature_lab.text = temperature;
        self.date_lab.text = date;
        //通过sd_webImage设置图片
        [self.weather_img sd_setImageWithURL:todayWeather_data[@"dayPictureUrl"]];
        
        NSURL *weather_url = todayWeather_data[@"dayPictureUrl"];
    
        
        self.weather_lab.text = weather;
        self.temperature_lab.text = temperature;
        self.date_lab.text = date;
        [self.weather_img sd_setImageWithURL:weather_url];
        
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nullable JSON) {
        NSLog(@"失败");
    }];
    

}


- (UIView *)PhotoView {
    if (_PhotoView == nil) {
        _PhotoView = [[UIView alloc] init];
        _PhotoView.backgroundColor = [UIColor redColor];
    }
    return _PhotoView;
}

- (UIView *)titleView {
    if (_titleView == nil) {
        _titleView = [[UIView alloc] init];
        _titleView.backgroundColor = [UIColor whiteColor];
    }
    return _titleView;
}

- (OKBottomView *)bottomView {
    if (_bottomView == nil) {
        _bottomView = [[OKBottomView alloc] init];
        _bottomView.backgroundColor = [UIColor lightGrayColor];
    }
    return _bottomView;
}

- (MOProductViewController *)product {
    
    if (_product == nil) {
        _product = [[MOProductViewController alloc]init];
    }
    return _product;
}

- (MOEntryViewController *)entry {
    
    if (_entry == nil) {
        _entry = [[MOEntryViewController alloc]init];
    }
    return _entry;
}

//- (NSString *)city_name{
//    if (_city_name == nil) {
//        _city_name = @"深圳";
//    }
//    _city_name =@"深圳";
    //NSLog(@"%@",_city_name);

//    return _city_name;
//}

#pragma mark - Custom Accessors
- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
    }
    return _locationManager;
}

- (CLGeocoder *)geocoder {
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc] init];
    }    return _geocoder;
}

- (void)requestLocationAutoorize {
    CGFloat systemVersion = [[UIDevice currentDevice].systemVersion floatValue];
    if (systemVersion >= 8) {
        [_locationManager requestAlwaysAuthorization];
    }
}
- (void)GetCurrentLocation {
    if ([CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务已开启");
        [_locationManager requestAlwaysAuthorization];
        [_locationManager startUpdatingLocation];
        self.locationManager.distanceFilter = kCLDistanceFilterNone;
    } else {
        NSLog(@"定位功能不能开启");
    }
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations firstObject];
    //NSLog(@"纬度=%f, 精度=%f",location.coordinate.latitude,location.coordinate.longitude);
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placeMark = [placemarks firstObject];
        //NSLog(@"%@",placeMark.locality);
        city = placeMark.locality;
        
        if (!istap) {
            // NSLog(@"%d",self.isTap);
            istap = YES;
            [self.city_but setTitle:city forState:UIControlStateNormal];
            
            self.city_name = city;
            [self networkRequests];
        }
        // NSLog(@"%@",city);
        
    }];
    [_locationManager stopUpdatingLocation];
    
    
}

#pragma mark -  HHLunBoDelegate
- (void)HHLunBoJumpToCharity{
    NQCharityActivity *vc = [[NQCharityActivity alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (HHLunBo *)LunBoView {
    if (_LunBoView == nil) {
        _LunBoView = [[HHLunBo alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        _LunBoView.delegate = self;
    }
    return _LunBoView;
}

- (NSMutableDictionary *)data {
    if (_data == nil) {
        _data = [NSMutableDictionary dictionary];
    }
    return _data;
}

- (UIImageView *)imgViewHH {
    if (_imgViewHH == nil) {
        _imgViewHH = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xianhua"]];

    }
    return _imgViewHH;
}

- (UILabel *)labelHH {
    if (_labelHH == nil) {
        _labelHH = [[UILabel alloc] init];
        _labelHH.text = @"名医通";
        _labelHH.font = [UIFont systemFontOfSize:20];
        _labelHH.textColor = [UIColor darkGrayColor];
    }

    return _labelHH;
}

@end







